import cv2 as cv
import time
import threading



def main():
    time1,time2 = time.time(), time.time()

    print(cv.__version__)

    cap = cv.VideoCapture(0+cv.CAP_V4L2)
    width = 1280 #1920  # 定义摄像头获取图像宽度
    height = 960 #1080  # 定义摄像头获取图像长度
    fps = 60
    cap.set(6, cv.VideoWriter_fourcc('M', 'J', 'P', 'G')) # 设置图像的编码格式
    cap.set(cv.CAP_PROP_FPS, fps)  # 帧率
    cap.set(cv.CAP_PROP_FRAME_WIDTH, width)  # 设置宽度
    cap.set(cv.CAP_PROP_FRAME_HEIGHT, height)  # 设置高度

    #设置图像保存格式与路径
    fourcc = cv.VideoWriter_fourcc('M','J','P','G')
    out = cv.VideoWriter('output4.avi',fourcc, 60, (1280,960))

    startflag=True #输出进程开始标识
    ret = True

    def func(): #输出线程
        now_time, last_time= time.time(), time.time()
        time.sleep(1) #等待主循环开始
        while(ret):
            time3 = time.time()
            last_time = now_time
            now_time=time.time() #记录开始处理之前
            p = now_time - last_time
            fps = 1 / p
            
            # 以下程序需要确保执行时间在 1000÷FPS内。
            hsv_frame = cv.cvtColor(frame, cv.COLOR_RGB2HSV)
            out.write(hsv_frame)
            cv.putText(hsv_frame, "{:.1f}".format(fps), (10, 30), cv.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv.LINE_AA)
            cv.imshow("frame",hsv_frame)
            time4=time.time()#记录处理之后的时间
            #等待函数。减去处理所用时间，用于减少误差
            # cv.waitKey(int(16-(time4-time3))) #这个50就是 1000÷输出FPS 因为要导出20FPS所以就是50
            if cv.waitKey(int(10-(time4-time3))) == ord('q'):
                break
    

    thread = threading.Thread(target=func) #创建线程
    thread.start() #开始线程
    
    print(cap.get(cv.CAP_PROP_FPS))

    #while(cap.isOpened()):
    while True:
        time1 = time.time()
        ret, frame = cap.read()
        if not ret:
            print("Can't receive frame (stream end?). Exiting ...")
            break
        time2 = time.time()

        time.sleep(int(16-(time2-time1))/1000)#与21行相同，由于原视频是30FPS，“int(”右边的数就是33（因为不能是小数）

        if thread.is_alive() == False:
            break
        # #旋转图像
        # #frame = cv.flip(frame, 0)
        # # out.write(frame)
        # cv.putText(frame, "{:.2f}".format(fps), (10, 30), cv.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv.LINE_AA)
        # # cv.putText(frame, str(cap.get(cv.CAP_PROP_FPS)), (10, 30), cv.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv.LINE_AA)
        # cv.imshow('frame', frame)

        # if cv.waitKey(1) == ord('q'):
        #     break

    thread.join()
    # Release everything if job is finished
    cap.release()
    out.release()
    cv.destroyAllWindows()


if __name__ == '__main__':
    main()
